package com.businessportal.web.controllers.calendar;

import com.businessportal.web.common.longtask.LongTasker;
import com.businessportal.web.common.longtask.tasks.NotificationCheckTask;
import com.businessportal.web.dataaccess.entities.Event;
import com.businessportal.web.dataaccess.entities.Login;
import com.businessportal.web.dataaccess.services.EventService;
import com.businessportal.web.dataaccess.services.UserService;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;

/**
 * Created by Vadim on 7/3/14.
 */
@WebServlet(urlPatterns = "/publicpages/calendar_viewer.do")
public class CalendarViewerController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");

            HttpSession session = req.getSession();
            Login user = (Login)session.getAttribute("user");

            req.setAttribute("events", EventService.INSTANCE.getAllPublicEvents(user));

        } catch(Exception e){
            req.setAttribute("errors", e.getMessage());
            req.setAttribute("events", new HashSet<Event>());
        }

        LongTasker.Execute(new NotificationCheckTask());


        getServletContext().getRequestDispatcher("/publicpages/calendar_viewer.jsp").forward(req, resp);
    }

    /**
     * We are using this endpoint to get description of the event
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setHeader("Cache-Control", "nocache");
        JSONObject retVal=new JSONObject();

        try {
            req.setCharacterEncoding("UTF-8");

            Long event_id = Long.parseLong(req.getParameter("event_id"));

            HttpSession session = req.getSession();
            Login user = (Login)session.getAttribute("user");

            if(0 != event_id){
                Event event = EventService.INSTANCE.getEventById(event_id);

                byte [] arr = Base64.encodeBase64(event.getDescription().getBytes("UTF-8"));

                retVal.put("description", new String(arr));
            } else {
                throw new Exception("Not found");
            }

        } catch (Exception e) {
            retVal.put("error", e.getMessage());
        }

        resp.getWriter().write(retVal.toString());
    }
}
